import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'
import { useAuthStore } from '@/stores/auth'

// 创建axios实例
const request = axios.create({
    baseURL: '/api',
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json;charset=UTF-8'
    }
})

let loadingInstance = null

// 请求拦截器
request.interceptors.request.use(
    (config) => {
        // 显示加载提示（针对非GET请求或需要长时间处理的请求）
        if (config.method !== 'get' && !config.hideLoading) {
            loadingInstance = ElLoading.service({
                lock: true,
                text: '加载中...',
                background: 'rgba(0, 0, 0, 0.7)'
            })
        }

        // 使用新的store获取token
        const authStore = useAuthStore()
        const loginEmp = authStore.getLoginEmp()

        if (loginEmp.token) {
            config.headers['token'] = loginEmp.token
        }

        // 处理GET请求参数
        if (config.method === 'get' && config.params) {
            let url = config.url + '?'
            for (const propName of Object.keys(config.params)) {
                const value = config.params[propName]
                if (value !== undefined && value !== null && value !== '') {
                    if (typeof value === 'object') {
                        for (const val of value) {
                            url += `${propName}=${encodeURIComponent(val)}&`
                        }
                    } else {
                        url += `${propName}=${encodeURIComponent(value)}&`
                    }
                }
            }
            url = url.substring(0, url.length - 1)
            config.params = {}
            config.url = url
        }

        return config
    },
    (error) => {
        loadingInstance?.close()
        return Promise.reject(error)
    }
)

// 响应拦截器
request.interceptors.response.use(
    (response) => {
        loadingInstance?.close()

        const { data } = response
        if (data.code === 1) {
            return data
        } else {
            ElMessage.error(data.msg || '请求失败')
            return Promise.reject(new Error(data.msg || '请求失败'))
        }
    },
    (error) => {
        loadingInstance?.close()

        if (error.response?.status === 401) {
            // 使用新的store方法清除登录信息
            const authStore = useAuthStore()
            authStore.removeLoginEmp()
            window.location.href = '/admin/login'
            ElMessage.error('登录已过期，请重新登录')
        } else if (error.response?.status === 403) {
            ElMessage.error('没有权限访问该资源')
        } else if (error.response?.status === 404) {
            ElMessage.error('请求的资源不存在')
        } else if (error.response?.status === 500) {
            ElMessage.error('服务器内部错误')
        } else if (error.code === 'ECONNABORTED') {
            ElMessage.error('请求超时')
        } else {
            ElMessage.error(error.response?.data?.msg || '网络错误')
        }

        return Promise.reject(error)
    }
)

export default request
